package com.chengzhi.leetcode;

import java.util.Objects;

/**
 * @description: 字符串压缩。利用字符重复出现的次数，编写一种方法，实现基本的字符串压缩功能。
 * 比如，字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短，则返回原先的字符串。你可以假设字符串中只包含大小写英文字母（a至z）
 * @author: ruanchengzhi
 * @create: 2020-03-16 11:08
 **/
public class CompressString {

    public static void main(String[] args) {
        String temp = "bb";
        System.out.println(compressString(temp));
    }

    public static String compressString(String S) {
        if (Objects.isNull(S) || S.length() <= 0) {
            return "";
        }
        StringBuffer buffer = new StringBuffer();
        char now = S.charAt(0);
        int index = 1;
        for (int i = 1; i < S.length(); i++) {
            char c = S.charAt(i);
            if (now == c) {
                index++;
            } else {
                buffer.append(now).append(index);
                index = 1;
                now = c;
            }
        }
        buffer.append(now).append(index);
        return buffer.toString().length() < S.length() ? buffer.toString() : S;
    }
}
